#!/usr/bin/env python
#
# Code and following comment are based on the default implementation created by google app engine launcher tool
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from time import strftime

#show time so we know it has refreshed
def getPrintMessage(title):
  return '<h1>'+title+'</h1> <p>server started at: '+strftime('%Y-%m-%d %H:%M:%S')+'</p>'

class P1Handler(webapp.RequestHandler):
  def get(self):
    self.response.out.write(getPrintMessage('p1'))
        
  def post(self):
    self.response.out.write('OK')

class P2Handler(webapp.RequestHandler):
  def get(self):
    self.response.out.write(getPrintMessage('p2'))
        
  def post(self):
    resp = self.request.get('certificate')
    self.response.out.write(resp)

class P3Handler(webapp.RequestHandler):
  def runUnitTests(self):
    
    import sys
    #load our vendor packages
    sys.path.insert(0, 'simplejson.zip')
    sys.path.insert(1, 'pyasn1.zip')
    sys.path.insert(2, 'keyczar.zip')
    sys.path.insert(3, 'keyczar_test.zip')
    from keyczar_test.alltests import *
    
    import StringIO
    import sys

    new_stdout = StringIO.StringIO()
    try:
      testResults = unittest.TextTestRunner(stream=new_stdout, verbosity=2).run(suite())
      
    except:
      pass
    
    return new_stdout.getvalue()
    
  def get(self):
    self.response.out.write(getPrintMessage('p3'))
    self.response.out.write(self.runUnitTests().replace('\n','<br/>'))
        
  def post(self):
    self.response.out.write(self.runUnitTests().replace('\n','<br/>'))

def main():
  application = webapp.WSGIApplication([('/p3', P3Handler),
                                       ('/p2', P2Handler),
                                       ('/.*',  P1Handler)],
                                       debug=True)
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()
